package model;


import com.google.appengine.api.datastore.Blob;
import com.google.appengine.api.datastore.Text;
import com.tecnick.htmlutils.htmlentities.HTMLEntities;

import controller.Controller;


import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;


public class MailingManager {
	private static MailingManager inst= new MailingManager();
	
	String fromName = "synca";
	String fromMail = "syncateam@gmail.com";

	
	public String getFromName() {
		return fromName;
	}

	public void setFromName(String fromName) {
		this.fromName = fromName;
	}
	HashMap<String, String> hebChr;
	private MailingManager(){
		hebChr = new HashMap<String, String>();
		hebChr.put("&#1514", "ת");
	}
	
	public static MailingManager getInst(){
		return inst;
	}
	
	
	public void sendMail(String to, String subject ,String msgBodyText)
	{
		//UserService userService = UserServiceFactory.getUserService();
		//fromMail = userService.getCurrentUser().getEmail();
		
		System.out.println("from mail: "+fromMail);
		System.out.println("send mail function");
		Properties props = new Properties();
		Session session = Session.getDefaultInstance(props, null);
		
		try {
			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(new InternetAddress(fromMail, fromName,"UTF-8"));
	        msg.addRecipient(Message.RecipientType.TO,
	                             new InternetAddress(to));
	        msg.setSubject(subject,"UTF-8");
	        
	        
	        msg.setContent(msgBodyText, "text/html");
	        
	        /*
	        //////////////////
	     // Unformatted text version
	        MimeBodyPart textPart = new MimeBodyPart();
	        textPart.setText(msgBodyText);
	        // HTML version
	        MimeBodyPart htmlPart = new MimeBodyPart();
	        htmlPart.setContent(msgBodyHtml, "text/html");
	        // Create the Multipart.  Add BodyParts to it.
	        Multipart mp = new MimeMultipart();
	        mp.addBodyPart(textPart);
	        mp.addBodyPart(htmlPart);
	        msg.setContent(mp);
	        ///////
	        */
	        
	        System.out.println("sending.. to "+to+" from "+fromMail);
	        Transport.send(msg);
	        System.out.println("end to send");
		} catch (AddressException e) {	
	            // ...
			e.printStackTrace();
		} catch (MessagingException e) {
	            // ...
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
		} 
	        
	}
	
	public void greetingMailClient(String clientName, String password, String email)
	{
		String syncaWebAddress = Controller.getInstance().getSyncaWebAddress();
		setFromName("Synca");
		String msgBody = "Hi "+clientName+",<br>"+
		"Thanks for joining Synca!<br>"+"your account details are:<br>"+"user name: "+clientName+"<br>"
		+ "password: "+password+"<br><br>"+ "hope you will enjoy,<br>"+"Synca team.<br><br>" +
		"<a href='"+syncaWebAddress+"'>"+"click here to get to synca site"+"</a><br>"+
		 "<img src='http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl="+syncaWebAddress+"'></img>"
		+ "<br><br>"+ "Synca team"
		+ "<br><br><br>"+"This message is automatically generated. Please do not respond to this mail.";
		
		sendMail(email, "welcome to synca! =) ", msgBody);
	}

	public void greetingMailBiz(String userName, String password, String email) {
		String syncaWebAddress = Controller.getInstance().getSyncaWebAddress();
		setFromName("Synca");
		String msgBody = "Hi "+userName+",<br>"+
		"Thanks for joining Synca!<br>"+"your account details are:<br>"+"user name: "+userName+"<br>"
		+ "password: "+password+"<br><br>"+ "hope you will enjoy,<br>"+"Synca team.<br><br>" +
		"<a href='"+syncaWebAddress+"'>"+"click here to get to synca site"+"</a><br>"+
		 "<img src='http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl="+syncaWebAddress+"'></img>"
		+ "<br><br>"+ "Synca team"
		+ "<br><br><br>"+"This message is automatically generated. Please do not respond to this mail.";
				
		sendMail(email, "welcome to synca! =) ", msgBody);
		
	}
	

	public void newOrderMail(String bizUserName, Integer orderID, String clientName, 
			String details, String address, String phone, String email, boolean isMailOrder, Blob blob) {
		String syncaWebAddress = Controller.getInstance().getSyncaWebAddress();
						
		String bizName = Controller.getInstance().userNameToBizName(bizUserName);
		setFromName(HTMLEntities.unhtmlentities(bizName));
		String msgBody = "Hi "+clientName+",<br>"+"new order was created.<br>"+"order info: <br>"+
		"business name: "+bizName+ "<br>" +"order id: "+orderID.toString()+"<br>"+"address: "+address+"<br>"+ "phone: "+phone+"<br>"
		+ "details: "+details +"<br><br>" + "in order to see your order "+
		"<a href='"+syncaWebAddress+"/showOneOrder.jsp?orderNum="+orderID+"&bizName="+bizUserName+"&phone="+phone+"'>"+
		"click here"+"</a><br><br>"+"<img src='http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl="
		+syncaWebAddress+"/showOneOrder.jsp?orderNum="+orderID+"%26bizName="+bizUserName+"%26phone="+phone+"'></img>"	
		+ "<br><br>"+ bizName;
		
		if (isMailOrder)
		{
			msgBody+="<br><br><a href='"+syncaWebAddress+"/business/cancelSendToOrderMail?orderID="+orderID+
			"&businessName="+bizName+"'>if you don't want to get any notification about this order - click here </a>";
		}
		if (Controller.getInstance().getBiz(bizUserName).getLogoPic()!=null)
			msgBody+="<img src=\"/showImage?imageKey=<%=i.getBusinessUserName() %>\" width=\"50\" /><br>powered by Synca<br>";
		msgBody+="<br><br><br>"+"This message is automatically generated. Please do not respond to this mail.";
		
		
		sendMail(email, "new order from "+HTMLEntities.unhtmlentities(bizName)+" - order number "+orderID, msgBody);	
		
	}

	public void forgetPassword(String userName , String password, String email) {
		String syncaWebAddress = Controller.getInstance().getSyncaWebAddress();
		setFromName("Synca");
		String msgBody = "Hi "+userName+",<br>"+
		"your password is: "+password+"<br><br>"+"Synca team.<br><br>"+
		"<a href='"+syncaWebAddress+"'>"+"click here to get to synca site"+"</a><br>"+
		 "<img src='http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl="+syncaWebAddress+"'></img>"
		+ "<br><br><br>"+"This message is automatically generated. Please do not respond to this mail.";
		
		sendMail(email, "synca password remainder", msgBody);
		
	}
	
	public void changeStatusMail(String userNameClient,String bizUserName, int orderID, String oldStatus, String newStatus, String phone,String email, boolean isMailOrder) throws UnsupportedEncodingException
	{
		
		String syncaWebAddress = Controller.getInstance().getSyncaWebAddress();
		String bizName = Controller.getInstance().userNameToBizName(bizUserName);
		setFromName(HTMLEntities.unhtmlentities(bizName));
		String msgBody = "Hi "+userNameClient+",<br>"+"status of order has changed.<br>"+"order details: <br>"+
		"business name: "+bizName+ "<br>" +"order id: "+orderID+"<br>"+"old status: "+oldStatus+"<br>"+
		"new status: "+newStatus+"<br><br>" + "in order to see your order "+
		"<a href='"+syncaWebAddress+"/showOneOrder.jsp?orderNum="+orderID+"&bizName="+bizUserName+"&phone="+phone+"'>"+"click here"+"</a><br><br>"+
		"<img src='http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl="+syncaWebAddress+
		"/showOneOrder.jsp?orderNum="+orderID+"%26bizName="+bizUserName+"%26phone="+phone+"'></img>"	
		+ "<br><br>"+ bizName; 

		if (isMailOrder)
		{
			msgBody+="<br><br><a href='"+syncaWebAddress+"/business/cancelSendToOrderMail?orderID="+orderID+
			"&businessName="+bizName+"'>if you don't want to get any notification about this order - click here </a>";
		}
		if (Controller.getInstance().getBiz(bizUserName).getLogoPic()!=null)
			msgBody+="<img src=\"/showImage?imageKey=<%=i.getBusinessUserName() %>\" width=\"50\" /><br>powered by Synca<br>";
		
		msgBody+="<br><br><br>"+"This message is automatically generated. Please do not respond to this mail.";

		sendMail(email, "status of order changed - order from "+HTMLEntities.unhtmlentities(bizName)+" order number "+orderID, msgBody);
	}
	
	public void newMessageMail(String userNameClient,String bizUserName, int orderID,String phone, String message, String email, boolean isMailOrder)
	{
		String syncaWebAddress = Controller.getInstance().getSyncaWebAddress();
		String bizName = Controller.getInstance().userNameToBizName(bizUserName);
		setFromName(HTMLEntities.unhtmlentities(bizName));
		
		String msgBody = "Hi "+userNameClient+",<br>"+"new message accepted.<br>"+"order details: <br>"+
		"business name: "+bizName+ "<br>" +"order id: "+orderID+"<br>"+"new message: "+message+"<br>"+
		"in order to see your order "+
		"<a href='"+syncaWebAddress+"/showOneOrder.jsp?orderNum="+orderID+"&bizName="+bizUserName+"&phone="+phone+"'>"+"click here"+"</a><br><br>"+
		"<img src='http://chart.apis.google.com/chart?cht=qr&chs=200x200&chl="+syncaWebAddress+
		"/showOneOrder.jsp?orderNum="+orderID+"%26bizName="+bizUserName+"%26phone="+phone+"'></img>"	
		+ "<br><br>"+ bizName;
		
		if (isMailOrder)
		{
			msgBody+="<br><br><a href='"+syncaWebAddress+"/business/cancelSendToOrderMail?orderID="+orderID+
			"&businessName="+bizName+"'>if you don't want to get any notification about this order - click here </a>";
		}
		if (Controller.getInstance().getBiz(bizUserName).getLogoPic()!=null)
			msgBody+="<img src=\"/showImage?imageKey=<%=i.getBusinessUserName() %>\" width=\"50\" /><br>powered by Synca<br>";
		
		msgBody+= "<br><br><br>"+"This message is automatically generated. Please do not respond to this mail.";
		
		sendMail(email, "new message - order from "+HTMLEntities.unhtmlentities(bizName)+" order number "+orderID, msgBody);	
	}

	private String convertToString(String str){
		if(!str.contains(";"))
			return str;
		String[] chars = str.split(";| ");
		StringBuffer newString = new StringBuffer();
		for(String chr : chars){
			if(chr.equals(""))
				newString.append(" ");
			else if(!chr.startsWith("&#"))
				newString.append(chr);
			else
				newString.append(intToByte(Integer.parseInt(chr.substring(2,6))-496));
			
		}
		return newString.toString();
	}
	
	public  String intToByte(int val){
		byte[] b = new byte[1];
		for(int i=0;i<1;i++){
			int offset = (b.length-1-i)*8;
			b[i]=(byte)((val>>>offset)&0xFF);
			
		}
		String s = "";
		try {
			s = new String(b,"UTF-8");
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return s;
	}

	public void contactSynca(String name, String email, String subject,
			String content) {	
		String msgBody = "name: "+name+"<br/>email: "+email+"<br/>subject: "+subject+"<br/>content: "+content;
		setFromName("Synca Site");
		sendMail(fromMail, "Contact Us",msgBody);
	}
}
